// index.js 
import { getSignature, decrypt } from '@wecom/crypto';
import getRawBody from 'raw-body';
import xml2js from 'xml2js';
import express from 'express'
var app = express();

// 在应用详情页找到对应的token
const token = 'BwMraz5UErPUWx3hSRib2ZE';
const aeskey = 'p13LZD5c7yYCg1OJE8VkictGRDzj34eZIoUgbYxfWYu';

app.get('/wechat/qy', (req, res) => {
    const { msg_signature, timestamp, nonce, echostr } = req.query;
    console.log(req.query, '12')
    const signature = getSignature(token, timestamp, nonce, echostr);
    console.log('signature', signature);
    // 校验签名是否正确
    if (signature === msg_signature) {
        console.info('签名验证成功');

        // 如果签名校验正确，解密 message
        const { message } = decrypt(aeskey, echostr);
        console.log('message', message);
        // 返回 message 信息
        res.send(message);
    }
});

function xml2jsFun(xml) {
    return new Promise(function (resolve, reject) {
      xml2js.parseString(
        xml,
        {
          trim: true,
        },
        (err, result) => {
          if (err) {
            reject();
          } else {
            resolve(result);
          }
        },
      );
    });
  }

app.post('/wechat/qy', async (req, res) => {
    const { msg_signature, timestamp, nonce, echostr } = req.query;
    // 重新计算签名
    const signature = getSignature(token, timestamp, nonce, echostr);
    console.log('signature', signature);
    let wholeXML = await getRawBody(req, {
        length: req.headers['content-length'],
        limit: '1mb',
        encoding: 'utf-8',
    });
    console.log(wholeXML, 'wholeXML')
    // 将 xml 解析成 json
    let formatJson = await xml2jsFun(wholeXML)
    formatJson = JSON.parse(JSON.stringify(formatJson, null, 4))
    // 得到加密消息体
    console.log(formatJson, 'formatJson')
    let encrypt = formatJson.xml.Encrypt[0];
    console.log(encrypt, 'encrypt')
    // 将加密消息体进行解密，解密后仍旧是 xml 字符串
    let messageXML = decrypt(aeskey, encrypt);
    // 把解密后 xml 消息体字符串，解析成 json
    let callbackDataBody = await xml2jsFun(messageXML.message);
    console.log('CallbackData', callbackDataBody);
    res.send('success')
});
app.listen(80);
console.log(80, '====')